<?php
namespace Admin\Model;
use Think\Model;
class UserModel extends Model{
	private $_id;
	private $_username;
	private $_password;
	private $_name;
	private $_role_id;

	public function checkUser($username, $password){
		$this->_username = $username;
		$this->_password = $password;
		$this->hashPassword();
		$res = $this->where(array('username'=>$username))->find();
		if($res['password'] == $this->_password){
			return $res;
		}else{
			return false;
		}
	}

	public function addUser($username, $password, $name, $rid){
		$this->_username = $username;
		$this->_password = $password;
		$this->_name = $name;
		$this->_role_id = $rid;
		if($this->checkPassword() && $this->checkUsername() && !$this->isHas()){
			$this->hashPassword();
			$data = array();
			$data['username'] = $this->_username;
			$data['password'] = $this->_password;
			$data['name'] = $this->_name;
			$data['role_id'] = $this->_role_id;
			return $this->add($data);
		}else{
			return false;	// 用户名或密码过于简单无法创建，不提供信息给前台显示，前台js判断
		}
	}

	public function resetPassword($uid, $newpassword){
		$this->_id = $uid;
		$this->_password = $newpassword;
		if($this->checkPassword()){
			$this->hashPassword();
			$data['id'] = $this->_id;
			$data['password'] = $this->_password;
			return $this->save($data);
		}
		return false;
	}

	public function getAdmins(){
		$map['role_id'] = array('NEQ', 0);	// 非普通用户即视为管理员用户
		return $this->where($map)->select();
	}


	private function checkUsername(){
		if(strlen($this->_username) == 18){	// 身份证号验证规则默认为18位字符串，如果需要修改，可以修改此函数
			return true;
		}
		return false;
	}

	private function hashPassword(){	// 对用户密码进行混淆。此处应该使用password_hash()函数，但由于该函数的版本要求较高，所以此处采用简单混淆
		$this->_password = md5($this->_password);
	}

	private function checkPassword(){	// 检测密码健壮性，仅在用户更新密码时用到
		if(strlen($this->_password) >= 6){	// 默认情况下只要密码长度大于等于6位即认为是安全的
			return true;
		}
		return false;
	}

	private function isHas(){
		if($this->where(array('username'=>$this->_username))->find() !=null){
			return true;
		}
		return false;
	}
}
